// pages/me/login/login.js
const app = getApp()
import { userLogin, authRegister, getuserInfo } from "../../../api/api.js";
import authLogin from '../../../utils/authLogin'
Page({
  data: {
    height: app.globalData.height * 2 + 30,
    nvabarData: {
      showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
      title: '登录 ', // 导航栏 中间的标题
      img: "../../image/back.png"
    },
    isShow: true,
    url: "/image/ty2.png",
    // hasUserInfo: false,
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    hasMobile: false,
    session_key: '',
    openid: ''
  },
  close_tap: function () {
    this.setData({
      isShow: true
    })
  },
  open_tap: function () {
    this.setData({
      isShow: false
    })
  },
  onLoad: function (options) {
    this.handleLoad();
  },
  
  getUserInfo: function(e){
    if (e.detail.errMsg == 'getUserInfo:ok') {
      const userinfo = JSON.parse(e.detail.rawData);
      const that = this;
      app.showLoading();
      authLogin().then(async res => {
        if (res.code == 0) {
          const openid = res.data.openid
          const session_key = res.data.session_key;
          const us = await getuserInfo({openid}).then(res => res);
          if (us.code == 0) {
            this.loginSuccess(us.data,openid);
          } else {
            that.changeApp(res.data, userinfo);
          }
          app.hideLoading();
        } else {
          console.log('获取openid失败');
        }
      })
    } else {
      console.log('用户拒绝授权获取用户信息');
    }
    return;
  },
  getPhoneNumber: function (e) {
    var that = this;
    app.showLoading();
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      const data = {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          session_key: that.data.session_key,
          openid: app.globalData.openid,
          avatar:  this.data.userInfo.avatarUrl,
          nickname: this.data.userInfo.nickName,
      }
      authRegister(data).then(res => {
        if (res.code === 0) {
          const openid = app.globalData.openid;
          getuserInfo({openid}).then(res => {
            this.loginSuccess(res.data,openid);
          });
        } else {
          app.showToast('注册失败','none',1000);
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/me/binding/binding' });
          }, 1000);
        }
        app.hideLoading();
      })
    } else {
      wx.navigateTo({
        url: '/pages/me/binding/binding',
      });
    }
  },

  // 更新app data数据
  changeApp (res, result) {
    // console.log(res);
    this.setData({
      session_key: res.session_key,
      hasUserInfo: true,
      userInfo: result
    });
    result.avatar = result.avatarUrl;
    app.globalData.hasLogin = true;
    app.globalData.openid = res.openid;
    app.globalData.userInfo = result; // res 整个user数据
  },

  backProv () {
    wx.navigateBack({ delta: 1 });
  },

  // 用户进来时 判断是否有授权获取用户头像和用户昵称
  // 没有的话 停止操作 
  // 有的话 获取用户头像 并判断是否已经注册 
  // 注册了的话 直接返回 并更新数据
  async handleLoad () {
    // 加载中
    app.showLoading();
    // 获取setting 判断是否有授权用户头像和用户昵称
    const setting = await this.gt_setting();
    // console.log(setting)
    if (setting.authSetting['scope.userInfo'] == true && setting.authSetting['scope.phoneNumber'] == true) {
      // 说明已经注册了
      // 拿用户信息
      const us = await getuserInfo({openid}).then(res => res);
      // console.log(us)
      if (us.code === 0) {
        this.loginSuccess(us.data);
      }
      return;
    }
    if (setting.authSetting['scope.userInfo'] == true) {
      // console.log('123')
      // 说明只授权了用户头像
      // 第一步 拿openid , session_key 保存起来
      // 第二步 拿openid 去判断用户是否注册
      // 第三步 注册了返回用户信息
      // 没有注册 拿到用户头像和用户昵称 保存起来
      const s = await authLogin();
      // console.log(s)
      if (s.code == 0) {
        const openid = s.data.openid;
        const session_key = s.data.session_key;
        // 获取用户信息
        const us = await getuserInfo({openid}).then(res => res);
        // 通过用户信息判断是否已经注册
        if (us.code === 0) {
          this.loginSuccess(us.data,openid);
        } else {
          // 用户未注册 拿userInfo数据保存起来 再退出
          const usinfo = await this.gt_getUserInfo();
          // console.log(usinfo);
          this.setData({
            openid,
            session_key,
            userInfo: usinfo,
            hasUserInfo: true
          });
          app.globalData.hasLogin = true;
          app.globalData.userInfo = usinfo;
          app.hideLoading();
        }
      } else {
        // 用户未授权 
        app.hideLoading();
        app.showToast(res.msg);
      }

    } else {
      app.hideLoading();
    }

  },

  // 获取授权信息
  gt_setting () {
    return new Promise((resolve,reject) => {
      wx.getSetting({
        success (res) {
          resolve(res);
        }
      })
    })
  },

  // 用户已授权 获取用户信息(微信头像和微信昵称)
  gt_getUserInfo() {
    return new Promise((resolve,reject) => {
      wx.getUserInfo({
        success (res) {
          resolve(JSON.parse(res.rawData));
        }
      })
    })
  },


  // 登陆成功 or 注册成功
  loginSuccess (user,openid) {
    const ap = app.globalData;
    // user.avatar = ap.imgUrl + user.avatar;
    ap.hasMobile = true;
    ap.hasLogin = true;
    ap.userInfo = user;
    ap.userId = user.id;
    ap.openid = openid;
    wx.navigateBack();
    return;
  }
 
})